package controllers.weixin;

import auth.WxMpAuth;
import helper.AliyunOssUploader;
import models.campus.Campus;
import models.campus.Room;
import models.contract.ContractCardRelation;
import models.contract.ContractRoom;
import models.enums.*;
import models.global.Image;
import models.issue.Issue;
import models.issue.IssueDetail;
import models.user.User;
import org.apache.commons.lang.StringUtils;
import play.mvc.Controller;
import play.mvc.With;
import sun.misc.BASE64Decoder;
import util.common.DateUtil;
import utils.WxCpMsgUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static jxl.biff.FormatRecord.logger;

/**
 * 报修Controller
 *
 */
@With(WxMpAuth.class)
public class IssueController extends Controller {

    public static void index(IssueType issueType) {
        System.out.println("issueType="+issueType.name());
        User user = WxMpAuth.currentUser();
        if(user == null) {
            String msg = "用户不能为空!";
            flash.error(msg);
            redirect("/");
        }
        System.out.println("用户ID"+user.id);
        List<ContractCardRelation> contractCardRelations  = ContractCardRelation.findAllByUser(user);
        if(contractCardRelations == null || contractCardRelations.size() == 0) {
            String msg = "请先绑定门禁卡!";
            flash.error(msg);
            redirect("/");
        }
        List<ContractCardRelation> contractCardRelationList = new ArrayList<ContractCardRelation>();
        Map<String,Object> map = new HashMap<String,Object>();
        for (ContractCardRelation contractCardRelation :contractCardRelations) {
            if(map.get(contractCardRelation.contract.id) == null) {
                map.put(contractCardRelation.contract.id,contractCardRelation);
                contractCardRelationList.add(contractCardRelation);
            }
        }
        List<IssueSubType> issueSubTypes = new ArrayList<IssueSubType>();
        if("REPAIR".equals(issueType.name())) {
            issueSubTypes.add(IssueSubType.WATER);
            issueSubTypes.add(IssueSubType.ELECTRIC);
            issueSubTypes.add(IssueSubType.COAL);
            issueSubTypes.add(IssueSubType.RENOVATION);
            issueSubTypes.add(IssueSubType.PHONE);
            issueSubTypes.add(IssueSubType.NETWORK);
            issueSubTypes.add(IssueSubType.OTHER);
            List<ContractRoom> contractRoomList = new ArrayList<ContractRoom>();
            for (ContractCardRelation contractCardRelation :contractCardRelationList) {
                System.out.println("合同Id"+contractCardRelation.contract.id);
                contractRoomList.addAll(ContractRoom.findByContract(contractCardRelation.contract));
            }
            renderArgs.put("phone",user.phone);
            render(contractRoomList , issueType , issueSubTypes);
        }else {
            issueSubTypes.add(IssueSubType.COMMON_FACILITIES);
            issueSubTypes.add(IssueSubType.DRAINAGE);
            issueSubTypes.add(IssueSubType.STREET_LAMP);
            issueSubTypes.add(IssueSubType.ENTRANCE_CONTROL);
            issueSubTypes.add(IssueSubType.OTHER);
            List<ContractRoom> contractRooms = new ArrayList<ContractRoom>();
            for (ContractCardRelation contractCardRelation :contractCardRelationList) {
                contractRooms.addAll(ContractRoom.findByContract(contractCardRelation.contract)) ;
            }
            List<Campus> campuses = new ArrayList<Campus>();
            Map<String,Object> campusMap = new HashMap<String,Object>();
            for (ContractRoom contractRoom : contractRooms) {
                Campus campus = contractRoom.room.building.campus;
                if(campusMap.get(campus.id) == null) {
                    campuses.add(campus);
                    campusMap.put(campus.id,campus);
                }
            }
            renderArgs.put("phone",user.phone);
            render(campuses , issueType , issueSubTypes);
        }
    }


    /**
     * 添加报修
     * @param issuesubtype
     * @param roomId
     * @param phone
     * @param issueName
     * @param remark
     */
    public static void repair(IssueType issueType, IssueSubType issuesubtype, String roomId,String campusId, String phone, String issueName, String remark,List<String> imgList, String visitStart, String visitEnd) {
        Map<String, Object> resultMap = new HashMap<>();
        User user = WxMpAuth.currentUser();
        Room room= Room.findByRoomId(roomId);
//        Campus campus = Campus.findByIdAndUnDeleted(campusId);

        if(StringUtils.isBlank(campusId) && room != null) {
            campusId = room.building.campus.id;
        }

        Date visitStartDate = DateUtil.stringToDate(visitStart, "yyyy-MM-dd HH:mm:ss");
        Date visitEndDate = DateUtil.stringToDate(visitEnd, "yyyy-MM-dd HH:mm:ss");

        Issue issue= new Issue(issueName, phone, user, room,campusId, issuesubtype, issueType, remark, visitStartDate, visitEndDate).save();
        new IssueDetail(issue, user.id,  OperatorType.USER, remark, IssueStatus.CREATE).save();
        if (imgList != null && imgList.size() > 0) {
            for(int i = 0;i < imgList.size();i++) {
                System.out.println("上传图片的路径："+imgList.get(i));
                if(issueType == IssueType.REPAIR){
                    new Image(imgList.get(i), ImageType.REPAIR, issue.getId() ,user).save();
                }else if(issueType == IssueType.COMPLAINT){
                    new Image(imgList.get(i), ImageType.PUBLIC_REPAIR, issue.getId() ,user).save();
                }
            }
        }
        WxCpMsgUtil.sendIssueCreateToClient(issue);
        resultMap.put("success", true);
        resultMap.put("msg", "报修内容提交成功");
        renderJSON(resultMap);
    }

    public static void uploadImg(String imgData,String imgPath ){
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] result = decoder.decodeBuffer(imgData.split(",")[1]);

            InputStream sbs = new ByteArrayInputStream(result);

            String realPath = AliyunOssUploader.uploadPublicFile(sbs, imgPath, result.length);

            renderJSON("{\"realPath\":\""+realPath+"\"}") ;
        } catch (IOException e) {
            logger.info("Log home/uploadImg error :" + e.getMessage());
            e.printStackTrace();
        }

        renderJSON("{\"realPath\":\"\"}") ;
    }


    public static void repairList() {
        User user = WxMpAuth.currentUser();
        if(user == null) {
            String msg = "用户不能为空!";
            flash.error(msg);
            redirect("/");
        }
        System.out.println("用户ID"+user.id);
        ContractCardRelation contractCardRelation  = ContractCardRelation.findByUser(user);
        if(contractCardRelation == null) {
            String msg = "请先绑定门禁卡!";
            flash.error(msg);
            redirect("/");
        }
        List<Issue> issueList = Issue.findByWeixinUserAndType(user,IssueType.REPAIR);
        render(issueList);
    }

    public static void publicRepairList() {
        User user = WxMpAuth.currentUser();
        if(user == null) {
            String msg = "用户不能为空!";
            flash.error(msg);
            redirect("/");
        }
        System.out.println("用户ID"+user.id);
        ContractCardRelation contractCardRelation  = ContractCardRelation.findByUser(user);
        if(contractCardRelation == null) {
            String msg = "请先绑定门禁卡!";
            flash.error(msg);
            redirect("/");
        }
        List<Issue> issueList = Issue.findByWeixinUserAndType(user, IssueType.COMPLAINT);
        render(issueList);
    }

    public static void issueDetail(String id) {
        Issue issue = Issue.findByIdAndUnDeleted(id);
        List<Image> images = Image.findByRecordId(issue.getId());
        render(issue, images);
    }

}
